package com.san.earlyWarning.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import com.san.base.controller.BaseController;
import com.san.common.annotation.Log;
import com.san.common.utils.ExcelUtil;
import com.san.common.utils.PageUtils;
import com.san.common.utils.Query;
import com.san.common.utils.R;
import com.san.earlyWarning.domain.EarlyWarningCompanyDO;
import com.san.earlyWarning.domain.EarlyWarningDO;
import com.san.earlyWarning.domain.WarningFollowDO;
import com.san.earlyWarning.service.EarlyWarningService;
import com.san.system.domain.UserDO;
import com.san.system.service.UserService;

/**
 * 信用预警
 * 版本升级，现已弃用
 * 整体功能由WarningsController.class替代
 * @author hulp
 * @date 2019年12月31日15:47:58
 *
 */
@Deprecated
@Controller
@RequestMapping("ew/warning")
public class EarlyWarningController extends BaseController {

	private String PREFIX = "ew/warning";
	private static final Logger logger = LoggerFactory.getLogger(EarlyWarningController.class);
	
	@Autowired
	EarlyWarningService earlyWarningService;
	
	@Autowired
	UserService userService;
	
	@GetMapping("")
	@RequiresPermissions("ew:warning:view")
	String view(Model model) {
		return PREFIX + "/view";
	}
	
	/**
	 * 查询信用预警列表
	 * @param params
	 * @return
	 */
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("ew:warning:view")
	public PageUtils list(@RequestParam Map<String, Object> params){
		PageUtils pageUtils = null;
		try{
			// 查询列表数据
			Query query = new Query(params);
			List<EarlyWarningDO> list = earlyWarningService.list(query);
			int total = earlyWarningService.count(query);
			pageUtils = new PageUtils(list, total);
		}catch(Exception e){
			logger.error("获取信用预警失败",e);
		}
		return pageUtils;
	}
	
	/**
	 * 添加预警页面
	 * @param model
	 * @return
	 */
	@GetMapping("/add")
	@RequiresPermissions("ew:warning:add")
	String add(Model model) {
		return PREFIX + "/add";
	}
	
	/**
	 * 添加预警页面
	 * @param earlyWarningDO
	 * @return
	 */
	@RequiresPermissions("ew:warning:add")
	@Log("添加预警页面")
	@PostMapping("/save")
	@ResponseBody
	R save(EarlyWarningDO earlyWarningDO) {
		try {
			if (earlyWarningService.save(earlyWarningDO) > 0) {
				return R.ok();
			}
		} catch (Exception e) {
			logger.error("保存信用预警出错", e);
			return R.error();
		}
		return R.error();
	}
	
	/**
	 * 控制信用预警状态
	 * @param id
	 * @param delFlag
	 * @return
	 */
	@PostMapping(value = "/changeStatus")
	@RequiresPermissions("ew:warning:changeStatus")
	@ResponseBody
	public R changeStatus(Long id,Long delFlag ) {
		String label = "";
		if (delFlag == 1) {
			label = "禁用";
		} else {
			label = "启用";
		}
		EarlyWarningDO earlyWarningDO = new EarlyWarningDO();
		earlyWarningDO.setWarnId(id);
		earlyWarningDO.setDelFlag(delFlag);
		try {
			earlyWarningService.changeStatus(earlyWarningDO);
			return R.ok("信用预警" + label + "成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.ok("信用预警" + label + "失败");
	}
	
	/**
	 * 删除信用预警
	 * 
	 * @param id
	 * @return
	 */
	@RequiresPermissions("ew:warning:remove")
	@Log("删除信用预警")
	@PostMapping("/remove")
	@ResponseBody
	R remove(Long id) {
		try {
			if (earlyWarningService.remove(id) > 0) {
				return R.ok();
			}
		} catch (Exception e) {
			logger.error("删除信用预警", e);
			return R.error();
		}
		return R.error("删除信用预警失败");
	}
	
	/**
	 * 编辑信用预警页面
	 * 
	 * @param model
	 * @param tableId 表ID
	 * @return
	 */
	@Log("编辑信用预警信息")
	@RequiresPermissions("ew:warning:edit")
	@GetMapping("/edit/{warnId}")
	String edit(Model model, @PathVariable("warnId") Long warnId) {
		EarlyWarningDO ewDO = null;
		try {
			ewDO = earlyWarningService.getById(warnId);
		} catch (Exception e) {
			logger.error("获取信用预警信息出错", e);
		}
		model.addAttribute("earlyWarning", ewDO);
		return PREFIX + "/edit";
	}
	
	/**
	 * 更新信用预警信息
	 * 
	 * @param technicalTableDO
	 * @return
	 */
	@RequiresPermissions("ew:warning:edit")
	@Log("更新信用预警")
	@PostMapping("/doEdit")
	@ResponseBody
	R doEdit(EarlyWarningDO earlyWarningDO) {
		try {
			if (earlyWarningService.doEdit(earlyWarningDO) > 0) {
				return R.ok();
			}
		} catch (Exception e) {
			logger.error("更新信用预警出错", e);
			return R.error();
		}
		return R.error();
	}
	
	/**
	 * 信用预警订阅页面
	 * @param model
	 * @return
	 */
	@GetMapping("/myFollow")
	@RequiresPermissions("ew:warning:follow")
	String myFollow(Model model) {
		return PREFIX + "/myFollow";
	}
	
	/**
	 * 查询我订阅的信用预警列表
	 * @param params
	 * @return
	 */
	@ResponseBody
	@GetMapping("/listMyFollow")
	@RequiresPermissions("ew:warning:follow")
	public PageUtils listMyFollow(@RequestParam Map<String, Object> params){
		PageUtils pageUtils = null;
		UserDO userDO;
		try{
			userDO = (UserDO) userService.getById(getUser().getUserId());
			Long deptId = userDO.getDeptId();
			// 查询列表数据
			Query query = new Query(params);
			query.put("deptId2", deptId);
			List<EarlyWarningDO> list = earlyWarningService.listFollow(query);
			int total = earlyWarningService.countFollow(query);
			pageUtils = new PageUtils(list, total);
		}catch(Exception e){
			logger.error("获取我订阅的信用预警列表失败",e);
		}
		return pageUtils;
	}
	
	/**
	 * 信用预警订阅页面
	 * @param model
	 * @return
	 */
	@GetMapping("/follow")
	@RequiresPermissions("ew:warning:follow")
	String follow(Model model) {
		return PREFIX + "/follow";
	}
	
	/**
	 * 查询信用预警订阅列表
	 * @param params
	 * @return
	 */
	@ResponseBody
	@GetMapping("/listFollow")
	@RequiresPermissions("ew:warning:follow")
	public PageUtils listFollow(@RequestParam Map<String, Object> params){
		PageUtils pageUtils = null;
		UserDO userDO;
		try{
			// 查询列表数据
			Query query = new Query(params);
			userDO = (UserDO) userService.getById(getUser().getUserId());
			Long deptId = userDO.getDeptId();
			query.put("deptId1", deptId);
			List<EarlyWarningDO> list = earlyWarningService.listFollow(query);
			int total = earlyWarningService.countFollow(query);
			pageUtils = new PageUtils(list, total);
		}catch(Exception e){
			logger.error("获取信用预警订阅列表失败",e);
		}
		return pageUtils;
	}
	
	/**
	 * 控制信用预警订阅状态
	 * @param id
	 * @param delFlag
	 * @return
	 */
	@PostMapping(value = "/changeFollowStatus")
	@RequiresPermissions("ew:warning:changeStatus")
	@ResponseBody
	public R changeFollowStatus(Long warnId,Long status ) {
		String label = "";
		if (status == -1) {
			label = "退订";
		} else {
			label = "订阅";
		}
		Long deptId = null;
		try {
			UserDO userDO = (UserDO) userService.getById(getUser().getUserId());
			deptId = userDO.getDeptId();
		} catch (Exception e) {
			logger.error("获取用户信息失败",e);
		}
		WarningFollowDO warningFollowDO = new WarningFollowDO();
		warningFollowDO.setWarnId(warnId);
		warningFollowDO.setStatus(status);
		warningFollowDO.setDeptId(deptId);
		try {
			if(status == -1) {
				// 退订预警
				earlyWarningService.followRemove(warningFollowDO);
				// 删除该预警的对应企业名单
				earlyWarningService.batchRemoveData(warnId, deptId);
				return R.ok("信用预警" + label + "成功");
			}else if(status == 0) {
				earlyWarningService.followAdd(warningFollowDO);
				return R.ok("信用预警" + label + "成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.ok("信用预警" + label + "失败");
	}
	
	@GetMapping("/followReview")
	@RequiresPermissions("ew:warning:followReview")
	String followReview(Model model) {
		return PREFIX + "/followReview";
	}
	
	/**
	 * 查询信用预警审核列表
	 * @param params
	 * @return
	 */
	@ResponseBody
	@GetMapping("/listFollowReview")
	@RequiresPermissions("ew:warning:followReview")
	public PageUtils listFollowReview(@RequestParam Map<String, Object> params){
		PageUtils pageUtils = null;
		try{
			// 查询列表数据
			Query query = new Query(params);
			List<WarningFollowDO> list = earlyWarningService.listFollowReview(query);
			int total = earlyWarningService.countFollowReview(query);
			pageUtils = new PageUtils(list, total);
		}catch(Exception e){
			logger.error("获取信用预警审核失败",e);
		}
		return pageUtils;
	}
	
	/**
	 * 审核信用预警订阅状态
	 * @param id
	 * @param delFlag
	 * @return
	 */
	@PostMapping(value = "/reviewFollowStatus")
	@RequiresPermissions("ew:warning:changeStatus")
	@ResponseBody
	public R reviewFollowStatus(Long followId,Long status ) {
		String label = "";
		if (status == 1) {
			label = "通过";
		} else {
			label = "拒绝";
		}
		WarningFollowDO warningFollowDO = new WarningFollowDO();
		warningFollowDO.setFollowId(followId);
		warningFollowDO.setStatus(status);
		try {
				earlyWarningService.reviewFollowStatus(warningFollowDO);
				return R.ok(label + "审核成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.ok(label + "审核失败");
	}
	
	/**
	 * 信用预警订阅页面
	 * @param model
	 * @return
	 */
	@GetMapping("/myFollowDetail/{warnId}")
	@RequiresPermissions("ew:warning:follow")
	String myFollowDetail(Model model, @PathVariable("warnId") Long warnId) {
		Long total = null;
		try {
			UserDO userDO = (UserDO) userService.getById(getUser().getUserId());
			Long deptId = userDO.getDeptId();
			total = earlyWarningService.myFollowCount(warnId,deptId);
		} catch (Exception e) {
			logger.error("获取信用预警信息出错", e);
		}
		model.addAttribute("warnId", warnId);
		model.addAttribute("total", total);
		return PREFIX + "/myFollowDetail";
	}
	
	/**
	 * 查询信用预警企业列表
	 * @param params
	 * @return
	 */
	@ResponseBody
	@GetMapping("/listMyFollowDetail")
	@RequiresPermissions("ew:warning:view")
	public PageUtils listMyFollowDetail(@RequestParam Map<String, Object> params){
		PageUtils pageUtils = null;
		try{
			// 查询列表数据
			UserDO userDO = (UserDO) userService.getById(getUser().getUserId());
			Long deptId = userDO.getDeptId();
			Query query = new Query(params);
			query.put("deptId", deptId);
			query.put("status", null);
			List<EarlyWarningCompanyDO> list = earlyWarningService.listMyFollowDetail(query);
			int total = earlyWarningService.CountMyFollowDetail(query);
			pageUtils = new PageUtils(list, total);
		}catch(Exception e){
			logger.error("获取信用预警失败",e);
		}
		return pageUtils;
	}
	
	/**
	 * 信用预警订阅页面
	 * @param model
	 * @return
	 */
	@GetMapping("/myFollowInWarning/{warnId}")
	@RequiresPermissions("ew:warning:follow")
	String myFollowInWarning(Model model, @PathVariable("warnId") Long warnId) {
		Long total = null;
		try {
			UserDO userDO = (UserDO) userService.getById(getUser().getUserId());
			Long deptId = userDO.getDeptId();
			total = earlyWarningService.myFollowCount(warnId,deptId);
		} catch (Exception e) {
			logger.error("获取信用预警信息出错", e);
		}
		model.addAttribute("warnId", warnId);
		model.addAttribute("total", total);
		return PREFIX + "/myFollowInWarning";
	}
	
	/**
	 * 查询信用预警企业列表
	 * @param params
	 * @return
	 */
	@ResponseBody
	@GetMapping("/listMyFollowInWarning")
	@RequiresPermissions("ew:warning:view")
	public PageUtils listMyFollowInWarning(@RequestParam Map<String, Object> params){
		PageUtils pageUtils = null;
		try{
			// 查询列表数据
			UserDO userDO = (UserDO) userService.getById(getUser().getUserId());
			Long deptId = userDO.getDeptId();
			Query query = new Query(params);
			query.put("deptId", deptId);
			query.put("status", 0);
			List<EarlyWarningCompanyDO> list = earlyWarningService.listMyFollowDetail(query);
			int total = earlyWarningService.CountMyFollowDetail(query);
			pageUtils = new PageUtils(list, total);
		}catch(Exception e){
			logger.error("获取信用预警失败",e);
		}
		return pageUtils;
	}
	
	/**
	 * 信用预警订阅页面
	 * @param model
	 * @return
	 */
	@GetMapping("/dataImport/{warnId}")
	@RequiresPermissions("ew:warning:follow")
	String dataImport(Model model, @PathVariable("warnId") Long warnId) {
		model.addAttribute("warnId", warnId);
		return PREFIX + "/dataImport";
	}
	
	/**
	 * 预警数据导入
	 * @param warnId
	 * @param file
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@PostMapping("/doCheck")
	@RequiresPermissions("ew:warning:view")
	@Log("预警数据导入")
	public R doCheck(@RequestParam(value="warnId",required=false)Long warnId,@RequestParam(value="excelFile",required=false)MultipartFile file,HttpServletRequest request,HttpServletResponse response) {
		int errorCount = 0;
		try{
			MultipartRequest multipartRequest = (MultipartRequest)request;
			MultipartFile excelFile = multipartRequest.getFile("excelFile");
			if(excelFile != null){
				String fileName = excelFile.getOriginalFilename();
				String type = fileName.substring(fileName.lastIndexOf(".")+1);
				if("xlsx".equals(type) || "xls".equals(type)){
					List<List<String>> datas = ("xlsx".equals(type) ? ExcelUtil.readXlsx(excelFile.getInputStream()) : ExcelUtil.readXls(excelFile.getInputStream()));
					//读取的内容后处理
					UserDO userDO = (UserDO) userService.getById(getUser().getUserId());
					Long deptId = userDO.getDeptId();
					//TODO:没有去重判断
					errorCount = earlyWarningService.batchAddData(warnId,deptId,datas);
				}else{
					return R.error("请导入Excel文件");
				}
			}
		} catch(Exception e) {
			logger.error("匹配核查模板失败",e);
		}
		return R.ok("失败条数："+ errorCount);
	}
	
}
